
package com.wa.nashorn;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus.Series;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.util.ClassUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class RestCallTemplate {
    public static final Charset DEFAULT_CHARSET;
    private RestTemplate template;
    private String url;
    private HttpMethod httpMethod;
    private Map<String, Object> variables;
    private HttpHeaders headers;
    private Object body;
    private int timeout;
    private RestHasErrorHandler hasErrorHandler;
    private static boolean romePresent;
    private static final boolean jaxb2Present;
    private static final boolean jackson2Present;
    private static final boolean jacksonPresent;

    private RestCallTemplate(RestTemplate template) {
        this.httpMethod = HttpMethod.POST;
        this.variables = new HashMap();
        this.headers = new HttpHeaders();
        this.timeout = 60000;
        this.template = template;
    }

    public static RestCallTemplate url(String url) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setOutputStreaming(false);
        RestTemplate template = new RestTemplate(requestFactory);
        template.setErrorHandler(new NoneResponseErrorHandler());
        List<HttpMessageConverter<?>> messageConverters = new ArrayList();
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(DEFAULT_CHARSET);
        stringConverter.setWriteAcceptCharset(false);
        messageConverters.add(stringConverter);
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter());
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());
        if (romePresent) {
        }

        if (jaxb2Present) {
            messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }

        if (jackson2Present) {
            messageConverters.add(new MappingJackson2HttpMessageConverter());
        } else if (jacksonPresent) {
            messageConverters.add(new MappingJackson2HttpMessageConverter());
        }

        template.setMessageConverters(messageConverters);
        RestCallTemplate restTemplate = new RestCallTemplate(template);
        restTemplate.url = url;
        restTemplate.hasErrorHandler = (statusCode) -> {
            return statusCode.series() == Series.CLIENT_ERROR || statusCode.series() == Series.SERVER_ERROR;
        };
        return restTemplate;
    }

    public RestCallTemplate method(String method) {
        this.httpMethod = this.getHttpMethod(method);
        return this;
    }

    private HttpMethod getHttpMethod(String method) {
        if (method != null) {
            HttpMethod[] var2 = HttpMethod.values();
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                HttpMethod httpMethod = var2[var4];
                if (httpMethod.name().equalsIgnoreCase(method)) {
                    return httpMethod;
                }
            }
        }

        return HttpMethod.POST;
    }

    public RestCallTemplate body(Object body) {
        this.body = body;
        return this;
    }

    public RestCallTemplate timeout(int timeout) {
        this.timeout = timeout;
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(timeout);
        this.template.setRequestFactory(requestFactory);
        return this;
    }

    public RestCallTemplate var(String name, Object o) {
        if (o == null) {
            return this;
        } else {
            this.variables.put(name, o);
            return this;
        }
    }

    public RestCallTemplate header(String name, String... value) {
        if (value == null) {
            return this;
        } else {
            this.headers.put(name, new ArrayList(Arrays.asList(value)));
            return this;
        }
    }

    public RestCallTemplate headers(Map<String, String> headers) {
        if (headers == null) {
            return this;
        } else {
            headers.forEach((k, v) -> {
                this.headers.put(k, Collections.singletonList(v));
            });
            return this;
        }
    }

    public ResponseEntity<byte[]> byteDataExecute() {
        HttpEntity httpEntity = new HttpEntity(this.body, this.headers);
        this.hasErrorHandler = (statusCode) -> {
            return false;
        };
        return this.template.exchange(this.url, this.httpMethod, httpEntity, byte[].class, this.variables);
    }

    public static QueryStringBuilder queryStringBuilder(Boolean urlencode) {
        return new QueryStringBuilder(urlencode);
    }

    private boolean hasError(HttpStatus statusCode) {
        return this.hasErrorHandler.hasError(statusCode);
    }

    public static String urlEncode(String url) {
        try {
            return URLEncoder.encode(url, DEFAULT_CHARSET.name());
        } catch (UnsupportedEncodingException var2) {
            var2.printStackTrace();
            return url;
        }
    }

    public static void main(String[] args) {
        System.out.println(new String((byte[])url("https://www.baidu.com").byteDataExecute().getBody()));
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
        romePresent = ClassUtils.isPresent("com.sun.syndication.feed.WireFeed", RestTemplate.class.getClassLoader());
        jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", RestTemplate.class.getClassLoader());
        jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", RestTemplate.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", RestTemplate.class.getClassLoader());
        jacksonPresent = ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", RestTemplate.class.getClassLoader()) && ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", RestTemplate.class.getClassLoader());
    }

    private static class NoneResponseErrorHandler implements ResponseErrorHandler {
        private NoneResponseErrorHandler() {
        }

        public boolean hasError(ClientHttpResponse response) throws IOException {
            return this.hasError(this.getHttpStatusCode(response));
        }

        private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
            try {
                HttpStatus statusCode = response.getStatusCode();
                return statusCode;
            } catch (IllegalArgumentException var4) {
                throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), this.getResponseBody(response), this.getCharset(response));
            }
        }

        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.series() == Series.CLIENT_ERROR || statusCode.series() == Series.SERVER_ERROR;
        }

        public void handleError(ClientHttpResponse response) throws IOException {
        }

        private byte[] getResponseBody(ClientHttpResponse response) {
            try {
                InputStream responseBody = response.getBody();
                if (responseBody != null) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
                    StreamUtils.copy(responseBody, out);
                    return out.toByteArray();
                }
            } catch (IOException var4) {
            }

            return new byte[0];
        }

        private Charset getCharset(ClientHttpResponse response) {
            HttpHeaders headers = response.getHeaders();
            MediaType contentType = headers.getContentType();
            return contentType == null ? RestCallTemplate.DEFAULT_CHARSET : (contentType.getCharset() == null ? RestCallTemplate.DEFAULT_CHARSET : contentType.getCharset());
        }
    }

    public static class QueryStringBuilder {
        private final Boolean urlEncode;
        private Map<String, List<Object>> queryMap;

        private QueryStringBuilder(Boolean urlencode) {
            this.queryMap = new HashMap();
            if (urlencode == null) {
                this.urlEncode = Boolean.FALSE;
            } else {
                this.urlEncode = urlencode;
            }

        }

        public QueryStringBuilder var(String name, Object o) {
            if (o == null) {
                return this;
            } else {
                List<Object> value = (List)this.queryMap.computeIfAbsent(name, (k) -> {
                    return new ArrayList();
                });
                value.add(o);
                return this;
            }
        }

        public QueryStringBuilder vars(Map<String, Object> vars) {
            if (vars == null) {
                return this;
            } else {
                vars.forEach((k, v) -> {
                    List<Object> value = (List)this.queryMap.computeIfAbsent(k, (r) -> {
                        return new ArrayList();
                    });
                    value.add(v);
                });
                return this;
            }
        }

        public String build() {
            StringBuilder query = new StringBuilder();
            this.queryMap.forEach((k, v) -> {
                if (v.size() == 1) {
                    query.append(this.wrapper(k)).append("=").append(this.wrapper(v.get(0))).append("&");
                } else {
                    for(int i = 0; i < v.size(); ++i) {
                        query.append(this.wrapper(k)).append(this.wrapper("[")).append(i).append(this.wrapper("]")).append("=").append(this.wrapper(v.get(i))).append("&");
                    }
                }

            });
            String queryStr = query.toString();
            if (queryStr.endsWith("&")) {
                queryStr = queryStr.substring(0, query.length() - 1);
            }

            return queryStr;
        }

        public Object wrapper(Object val) {
            return this.urlEncode && val != null ? RestCallTemplate.urlEncode(val.toString()) : val;
        }

        public String build(String url) {
            return url + (url.length() > 0 ? "?" : "") + this.build();
        }
    }

    public interface RestHasErrorHandler {
        boolean hasError(HttpStatus statusCode);
    }
}
